/**
 * Copyright (c) 2016-2019 人人开源 All rights reserved.
 *
 * https://www.renren.io
 *
 * 版权所有，侵权必究！
 */

package com.sew.sewweb.common.utils.jdbc;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import com.sew.sewweb.common.config.BaseConfig;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.sql.*;

/**
 * jdbc连接数据库工具类
 *
 * @author Mark sunlightcs@gmail.com
 */
public class JdbcUtils {
	private static final Logger log= LogManager.getLogger(JdbcUtils.class);
	public static JSONArray jdbc(String sql){
		JSONArray array = new JSONArray();
		Connection conn = null;
		Statement statement = null;
		ResultSet resultSet = null;
		int count ;
		try {
			log.info("进来啦！！！！");
			// 首先建立驱动
			Class.forName(BaseConfig.getConfig().getString("sqlserver-class-name"));
			// 驱动成功后进行连接
			conn = DriverManager.getConnection(BaseConfig.getConfig().getString("sqlserver-url"),
					BaseConfig.getConfig().getString("sqlserver-username"),BaseConfig.getConfig().getString("sqlserver-password"));

			log.info("连接成功");
			statement = conn.createStatement();
			if(sql.contains("select")){
				log.info("查询语句进来啦!");
				resultSet = statement.executeQuery(sql);
				log.info("执行sql后返回的结果=" + resultSet);
				// 获取列数
				ResultSetMetaData metaData = resultSet.getMetaData();
				int columnCount = metaData.getColumnCount();
				while (resultSet.next()) {
					cn.hutool.json.JSONObject jsonObj = new JSONObject();
					// 遍历每一列
					for (int i = 1; i <= columnCount; i++) {
						String columnName =metaData.getColumnLabel(i);
						String value = resultSet.getString(columnName);
						jsonObj.put(columnName, value);
						log.info("返回数据=" + jsonObj);
					}
					array.add(jsonObj);
				}
			}else if(sql.contains("insert") || sql.contains("update") || sql.contains("delete")){
				log.info("非查询语句进来啦!");
				count = statement.executeUpdate(sql);
				log.info("条数==" + count);
//				if(statement.getUpdateCount()>0){
//					log.info("同步成功进来啦!-----");
//					count = 1;
//				}else{
//					log.info("同步失败进来啦!---");
//					count = -1;
//				}
//				log.info("数据库返回条数=" + count);
				JSONObject jsonObject = new JSONObject();
				if(count>0){
					log.info("同步成功进来啦!");
					jsonObject.put("code","200");
					jsonObject.put("msg","添加成功");
					array.add(jsonObject);
				}else{
					log.info("同步失败进来啦!");
					jsonObject.put("code","500");
					jsonObject.put("msg","添加失败");
					array.add(jsonObject);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			// 第六步：关闭资源
			try {
				if (resultSet != null)
					resultSet.close();
				if (statement != null)
					statement.close();
				if (conn != null)
					conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return array;
	}
}
